package com.example.ai.service;

import com.example.ai.dto.question.QuestionResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;

import java.util.*;

@Slf4j
@Service
public class DeepseekService {

    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private static final int HISTORY_LIMIT = 10;
    
    @Value("${deepseek.api-key}")
    private String apiKey;
    
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    private final QuestionService questionService;

    public DeepseekService(RestTemplate restTemplate, ObjectMapper objectMapper, 
                          QuestionService questionService) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
        this.questionService = questionService;
    }

    public String chat(String prompt) {
        try {
            // 创建分页请求
            Pageable pageable = PageRequest.of(0, HISTORY_LIMIT);
            
            // 使用 QuestionService 获取历史记录
            Page<QuestionResponse> recentQuestions = questionService.getUserQuestions(pageable);
            List<QuestionResponse> historyList = recentQuestions.getContent();
            
            // 准备消息列表，包含历史记录
            List<Map<String, String>> messages = new ArrayList<>();
            
            // 添加系统消息
            messages.add(Map.of(
                "role", "system",
                "content", "你是一个智能学习辅助机器人，请根据我的问题，辅助我了解相关知识"
            ));
            
            // 添加历史对话（从旧到新）
            for (int i = historyList.size() - 1; i >= 0; i--) {
                QuestionResponse q = historyList.get(i);
                messages.add(Map.of(
                    "role", "user",
                    "content", q.getContent()
                ));
                messages.add(Map.of(
                    "role", "assistant",
                    "content", q.getAnswer()
                ));
            }
            
            // 添加当前问题
            messages.add(Map.of(
                "role", "user",
                "content", prompt
            ));

            // 准备请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 准备请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", messages);
            requestBody.put("stream", false);

            // 发送请求
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            Map<String, Object> response = restTemplate.postForObject(
                API_URL,
                request,
                Map.class
            );

            // 解析响应
            if (response != null && response.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                    return (String) message.get("content");
                }
            }

            throw new RuntimeException("Invalid response from Deepseek API");

        } catch (Exception e) {
            log.error("Error calling Deepseek API", e);
            throw new RuntimeException("Failed to get AI response: " + e.getMessage());
        }
    }
}